﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Office.Interop.Word;

namespace DusonFramework.Documents.Office.Word.Ms
{
    /// <summary>
    /// 辅助类
    /// 引用类库
    /// 1.Microsoft.Office.Core（Com组件：Miscrosoft Office {Office版本号} Object Library）
    /// 2.Microsoft.Office.Interop.Word
    /// 3.Microsoft.Office.Interop.Graph
    /// </summary>
    public class WordHelper
    {
        #region 插入表格

        public static bool InsertTable(Application word, Document doc, System.Data.DataTable dt, bool haveBorder, double[] colWidths)
        {
            try
            {
                object Nothing = System.Reflection.Missing.Value;
                int lenght = doc.Characters.Count - 1;
                object start = lenght;
                object end = lenght; 
                //表格起始坐标                
                Range tableLocation = doc.Range(ref start, ref end); 
                //添加Word表格                     
                Table table = doc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);
                if (colWidths != null)
                {
                    for (int i = 0; i < colWidths.Length; i++)
                    {
                        table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
                    }
                }                
                //设置TABLE的样式                
                table.Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;
                table.Rows.Height = word.CentimetersToPoints(float.Parse("0.8"));
                table.Range.Font.Size = 10.5F;
                table.Range.Font.Name = "宋体";
                table.Range.Font.Bold = 0;
                table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                if (haveBorder == true) //设置外框样式  
                {                                     
                    table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
                    table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; //样式设置结束                
                } for (int row = 0; row < dt.Rows.Count; row++)
                {
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
            finally { }
        }

        public static bool InsertTable(Application word, Document doc, System.Data.DataTable dt, bool haveBorder)
        {
            return InsertTable(word, doc, dt, haveBorder, null);
        }

        public static bool InsertTable(Application word, Document doc, System.Data.DataTable dt)
        {
            return InsertTable(word, doc, dt, false, null);
        }

        #endregion

        /// <summary>
        /// 页脚中插入页码（第X页/共X页）
        /// </summary>
        /// <param name="word"></param>
        public static void InsertAllPageNumber(Application word)
        {
            object missing = System.Reflection.Missing.Value;
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
            word.Selection.WholeStory();
            word.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;

            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter; //页脚                 
            word.Selection.TypeText("第");
            object page = WdFieldType.wdFieldPage;
            word.Selection.Fields.Add(word.Selection.Range, ref page, ref missing, ref missing);
            word.Selection.TypeText("页/共");
            object pages = WdFieldType.wdFieldNumPages;
            word.Selection.Fields.Add(word.Selection.Range, ref pages, ref missing, ref missing);
            word.Selection.TypeText("页");

            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
        }

        /// <summary>
        /// 获取Word中的颜色
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static WdColor GetWordColor(System.Drawing.Color c)
        {
            UInt32 R = 0x1, G = 0x100, B = 0x10000;
            return (WdColor)(R * c.R + G * c.G + B * c.B);
        }

        /// <summary>
        /// 创建图表
        /// </summary>
        /// <param name="EndOfDoc"></param>
        /// <param name="Doc"></param>
        /// <param name="Word"></param>
        /// <param name="xlcharttype"></param>
        public static void CreatChart(object EndOfDoc, _Document Doc, _Application Word, Microsoft.Office.Interop.Graph.XlChartType xlcharttype, System.Data.DataTable dtsheet)
        {
            Microsoft.Office.Interop.Graph.Axis axis;
            object _missing = System.Reflection.Missing.Value;

            _Document oDoc = Doc;
            _Application oWord = Word;
            object oEndOfDoc = EndOfDoc;

            object oClassType = "MSGraph.Chart.8"; // 加入一张图表，系统自带office控件；
            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            // 初始化一张图表
            Microsoft.Office.Interop.Graph.Chart wrdChart;
            wrdChart = (Microsoft.Office.Interop.Graph.Chart)wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref _missing,
            ref _missing, ref _missing, ref _missing,
            ref _missing, ref _missing, ref _missing).OLEFormat.Object;

            wrdChart.Application.PlotBy = Microsoft.Office.Interop.Graph.XlRowCol.xlColumns;//根据Y轴来画图表

            // 改变图表格式
            wrdChart.ChartType = xlcharttype; // 可以设置为饼状图

            axis = (Microsoft.Office.Interop.Graph.Axis)wrdChart.Axes(1, 1); //设置X轴的属性

            wrdChart.Application.DataSheet.Cells.Clear(); // 清空表格的初始数据

            // 填充图表,起始的行号和列号都是1
            int i, j;

            for (i = 0; i < dtsheet.Columns.Count; i++) // 初始化列名
            {
                wrdChart.Application.DataSheet.Cells[1, i + 1] = dtsheet.Columns[i].ColumnName;
            }
            for (i = 0; i < dtsheet.Rows.Count; i++) // 填充数据
            {
                for (j = 0; j < dtsheet.Columns.Count; j++)
                {
                    wrdChart.Application.DataSheet.Cells[i + 2, j + 1] = dtsheet.Rows[i][j].ToString().Replace("9999999 ", "100ys ");
                }
            }

            wrdChart.Width = 1000;

            wrdChart.Height = 1332;
            wrdChart.Height = oWord.InchesToPoints(3.57f);

            // 在图之后加入文字
            Range wrdRng1 = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            wrdRng1 = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            wrdRng1.InsertParagraphAfter();
            wrdRng1.InsertAfter("THE   END.");

            // 更新图表并保存退出
            wrdChart.Application.Update();
            wrdChart.Application.Quit();
        }

    }
}
